package org.usmile.algorithms.huawei.acm;

import java.util.Scanner;

// https://blog.csdn.net/qq_34465338/article/details/128596242
public class _机器人活动区域 {
    private static int[][] metric;
    private static boolean[][] visited;
    private static int rows;
    private static int cols;
    private static final int[][] directions = new int[][]{{-1, 0}, {1, 0}, {0, -1}, {0, 1}};

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        rows = sc.nextInt();
        cols = sc.nextInt();
        sc.nextLine();
        metric = new int[rows][cols];
        visited = new boolean[rows][cols];
        for (int row = 0; row < rows; row++) {
            String[] rowLine = sc.nextLine().split(" ");
            for (int col = 0; col < cols; col++) {
                metric[row][col] = Integer.parseInt(rowLine[col]);
            }
        }

        int max = 0;
        for (int row = 0; row < rows; row++) {
            for (int col = 0; col < cols; col++) {
                if (!visited[row][col]) {
                    max = Math.max(max, dfs(row, col));
                }
            }
        }

        System.out.println(max);
    }

    private static int dfs(int row, int col) {
        int count = 1;
        visited[row][col] = true;
        int curr = metric[row][col];
        for (int[] direction : directions) {
            int nextRow = row + direction[0];
            int nextCol = col + direction[1];
            if (nextRow >= 0 && nextRow < rows && nextCol >= 0 && nextCol < cols) {
                if (!visited[nextRow][nextCol]) {
                    int next = metric[nextRow][nextCol];
                    if (Math.abs(curr - next) <= 1) {
                        count += dfs(nextRow, nextCol);
                    }
                }
            }
        }

        return count;
    }
}
